
/**
   * 本地操作购物车数据数据
   * type:1:添加购物车；2：删除购物车
   */
function addCart(goodsData,count) {
  var carts = tt.getStorageSync("CARTS")
  if (!carts) {
    carts = [];
  }
  var oldIndex = -1;
  var isHad = false;
  for (var i = 0; i < carts.length; i++) {
    if (goodsData.skuId == carts[i].skuId) {
      carts[i].count = carts[i].count + count;
      isHad = true;
      oldIndex = i; //记录下修改的index;
      break;
    }
  }

  if (isHad == false) { //这里为新增购物车
    var curGoods = goodsData;
    curGoods.count = count;
    carts.push({ curGoods})
  }
  //将购物车保存在缓存中
  tt.setStorageSync("CARTS", carts)
  return carts;
}

//删除购物车
function subCarts(goodsData,count){
  var carts = tt.getStorageSync("CARTS")
  if (!carts) {
    carts = [];
  }
  for (var i = 0; i < carts.length; i++) {
    if (goodsData.skuId == carts[i].skuId) {
      carts[i].count = carts[i].count - count;
      break;
    } 
  }
  //将购物车保存在缓存中
  tt.setStorageSync("CARTS", carts)
  return carts;
}


//查询本地购物车
function queryLockCart() {
  let carts =  tt.getStorageSync('CARTS')
  if (carts) {
    return carts;
  } else {
    return [];
  }
}

module.exports = {
  queryLockCart,
  addCart,
  subCarts
}